<template>
  <!--按人员工分登记-->
  <BasicModal
    v-bind="$attrs"
    @register="register"
    title="按人员登记"
    @ok="handleSubmit"
    width="100%"
    :defaultFullscreen="true"
    :destroyOnClose="true"
    :showOkBtn="!isView"
    :okButtonProps="{
      loading: okLoading,
    }"
  >
    <div class="table-container">
      <!--左侧-人员树-->
      <list :options="userTree" @select="handleuserTree" ref="userList" />
      <div class="table-content" :style="{ marginLeft: '10px', width: 'self' === self ? '100%' : 'calc(100% - 260px)' }">
        <BasicForm @register="registerForm" />
        <div class="bot-container">
          <div class="table-container">
            <!--右侧-工分类型树-->
            <list :options="workTree" @select="handleWorkTree" ref="workList" />
            <!-- 右侧登记表 -->
            <div class="table-content">
              <BasicTable @register="registerTable">
                <template #bodyCell="{ column, text, record, index }">
                  <template v-if="column.editRow">
                    <a-input-number
                      :disabled="isView"
                      v-model:value="record[column.dataIndex]"
                      @change="scoreCompute"
                      v-if="'InputNumber' === column.editComponent && column.dataIndex === 'unit'"
                      @focus="handleIndex(index)"
                      :min="1"
                    />
                    <a-input-number
                      :disabled="isView"
                      v-model:value="record[column.dataIndex]"
                      @change="scoreCompute"
                      v-if="'InputNumber' === column.editComponent && column.dataIndex === 'qspoints'"
                      @focus="handleIndex(index)"
                    />
                    <a-select
                      :disabled="isView"
                      v-model:value="record[column.dataIndex]"
                      style="width: 100%"
                      @change="scoreCompute"
                      @focus="handleIndex(index)"
                      :options="column.options"
                      :fieldNames="{ label: 'workName', value: 'workCode' }"
                      v-else-if="'Select' === column.editComponent"
                    />
                    <a-input
                      :disabled="isView"
                      v-model:value="record[column.dataIndex]"
                      @change="scoreCompute"
                      v-else-if="column.dataIndex === 'workExpl'"
                    />
                  </template>
                </template>
                <template #action="{ record, index }">
                  <TableAction :actions="getTableAction(record, index)" />
                </template>
              </BasicTable>
            </div>
          </div>
        </div>
      </div>
    </div>
  </BasicModal>
</template>
<script setup>
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import List from '../../../components/pageList/list1.vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { pepColumns } from './HubTeamResultWork.data';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { createPoints, getTaskDetail, getUserOptions, getWorkTreeApi, getUserTreeApi, getColumn, save } from './HubTeamResultWork.api';
  import { unifyNumber } from '/@/views/zhc/util/numUtils';
  import { useMessage } from '/@/hooks/web/useMessage';
  import dayjs from 'dayjs';

  const props = defineProps({
    self: {
      type: String,
    },
  });
  let pageParams = ref({
    orgCode: '',
    orgName: '',
  });
  const okLoading = ref(false);
  let currentTableIndex = 0; //记录当前操作的表格数据行
  let isView = ref(false);
  const handleIndex = (index) => {
    currentTableIndex = index;
  };
  let userList = ref(null);
  let workList = ref(null);
  const { createMessage } = useMessage();

  const pepForm = [
    {
      label: '班员工号',
      field: 'psnNum',
      component: 'Input',
      show: false,
    },
    {
      label: '班员',
      field: 'psnName',
      component: 'Input',
      dynamicDisabled: () => true,
      colProps: { span: 12 },
    },
    {
      field: 'endDate',
      label: '发生日期',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
      defaultValue: dayjs(),
      dynamicDisabled: () => isView.value,
      required: true,
      colProps: { span: 12 },
    },
  ];

  const userTree = {
    url: getUserTreeApi,
    method: 'post',
    title: '参与人员选择',
    params: {
      orgCode: pageParams.value.orgCode,
    },
    fieldNames: {
      title: 'psnName', //替换树默认显示title字段
      key: 'psnNum',
    },
  };

  const workTree = ref({
    url: getWorkTreeApi,
    method: 'post', //请求方法类型 默认get
    title: '项目和类型',
    // params: {
    //   orgCode: pageParams.value.orgCode,
    //   periodCode: pageParams.value.orgCode,
    // },
    // checkable: true,
    selectedKeys: [],
    fieldNames: {
      title: 'title', //替换树默认显示title字段
      key: 'code',
    },
  });

  let projectData = []; //项目详情数据
  let selectorField = ref([]);
  let selectedUser = {
    psnName: '',
    psnNum: '',
    orgCode: '',
    orgName: '',
  };

  let selectedWork = {};

  let defaultData = {};
  let editid = null;

  // 声明Emits
  const emit = defineEmits(['success', 'register']);
  const [register, { closeModal = () => {}, setModalProps = (p) => {} }] = useModalInner(async (data) => {
    okLoading.value = false;
    currentRationCode = '';
    pageParams.value.orgCode = data.orgCode;
    pageParams.value.periodCode = data.periodCode;
    console.log('personModal', pageParams);
    editid = data.isEdit ? data.res.id : null;
    console.log('接收到的参数为：', pageParams.value.orgCode);
    console.log('收到页面参数', data);
    userTree.disabled = data.isView;
    workTree.value.disabled = data.isView;
    isView.value = data.isView;
    if (data.isEdit) {
      // 编辑状态
      let formSchema = [...pepForm];
      console.log('xxxa11', formSchema);
      resetSchema(formSchema);
      setFieldsValue({
        psnName: data.res.psnName,
        psnNum: data.res.psnNum,
        workItemCode: data.res.rationCode,
        endDate: dayjs(data.res.endDate),
        // standardValue: data.res.stdscore,
        // workQualityCriterion: data.res.qstandard,
      });
      selectedUser.psnName = data.res.psnName;
      selectedUser.psnNum = data.res.psnNum;
      selectedUser.orgName = data.res.orgName;
      selectedUser.orgCode = data.res.orgCode;
      userList.value.handleSelect([data.res.psnNum]);
      if (data.res.rationCode) workList.value.setTreeSelected(data.res.rationCode.split(','));
      currentRationCode = data.res.rationCode;
      let tableData = data.res.details || [];
      tableData = tableData.map((item) => {
        if (item.reamrk) {
          return {
            ...item,
            ...JSON.parse(item.reamrk),
          };
        }
      });
      console.log('tableData', tableData);
      setTableData(tableData);
    }
    console.log('111editid', editid);
    //动态表头设置 getTeamResultOrderXsHeader
    await getColumn({ orgCode: pageParams.value.orgCode }).then((res) => {
      let columns = [...pepColumns];
      console.log('isEdit', data.isEdit);
      try {
        res.forEach((r) => {
          //默认值设置
          if (r.datas && r.datas.length > 0) {
            r.datas.forEach((option) => {
              option.workName = option.workName + '(' + option.workCode + ')';
              if (option.isDefault === 'true' && !data.isEdit) {
                defaultData[r.headCode] = option.workCode;
              }
            });
          }
          // 在表格固定表头中插入动态表头
          columns.splice(columns.length - 5, 0, {
            title: r.headName,
            dataIndex: r.headCode,
            editRow: true,
            editComponent: 'Select',
            type: 2,
            width: 100,
            align: 'center',
            options: r.datas,
          });
        });
        console.log('11111defaultData', defaultData);
        setColumns(columns); //重设表头
      } catch (e) {
        console.error(e);
      }
    });
  });

  //表单配置
  const [registerForm, { setFieldsValue = () => {}, validate = () => {}, resetSchema = () => {} }] = useForm({
    schemas: pepForm,
    showActionButtonGroup: false,
  });
  let scrollY = computed(() => {
    let width = document.body.clientWidth;
    return width < 1500 ? 400 : 500;
  });

  let [registerTable, { getDataSource = () => {}, setTableData = () => {}, setColumns = () => {}, getColumns = () => {} }] = useTable({
    columns: pepColumns,
    rowKey: 'id',
    bordered: true,
    showActionColumn: true,
    pagination: false,
    actionColumn: {
      width: 60,
      title: '操作',
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: 'right',
    },
    scroll: { y: scrollY },
  });
  //表单提交事件
  async function handleSubmit() {
    try {
      let tableData = getDataSource();
      if (tableData.length === 0) {
        createMessage.error('数据不能为空！');
        return;
      }
      let flag = true;
      let rationNameList = [];
      let rationCodeList = [];
      tableData.forEach((t) => {
        rationNameList.push(t.rationName);
        rationCodeList.push(t.rationCode);
        if (!t.sumPoints) {
          flag = false;
        }
      });
      //校验积分是否有空值
      if (!flag) {
        createMessage.error('积分项不能为空');
        return;
      }
      setModalProps({ confirmLoading: true });
      //拼接参数
      let formValue = await validate();
      let saveData = {
        addMode: '20',
        ...selectedUser,
        rationName: Array.from(new Set(rationNameList)).join(),
        rationCode: Array.from(new Set(rationCodeList)).join(),
        // ...selectedWork,
        endDate: dayjs(formValue.endDate).format('YYYY-MM-DD'),
        // descr: formValue.workQualityCriterion,
        details: tableData,
        periodCode: pageParams.value.periodCode,
        // qstandard: formValue.workQualityCriterion,
        // stdscore: formValue.standardValue,
      };
      saveData.details?.forEach((item) => {
        // let sumScore = 0;
        item.reamrk = {};
        Object.keys(item).forEach((key) => {
          if (key.indexOf('XSP') != -1) {
            // sumScore += parseFloat(item[key]);
            item.reamrk = {
              ...item.reamrk,
              [key]: item[key],
              // sumPoints: sumScore,
            };
          }
          // item.sumPoints = sumScore;
        });
      });
      saveData.details?.forEach((item) => {
        item.addMode = '20';
        if (item.reamrk) {
          item.reamrk = JSON.stringify(item.reamrk);
        }
      });
      if (editid) {
        saveData.id = editid;
      }
      okLoading.value = true;
      console.log('tableData', tableData);
      console.log('saveData', saveData);
      save(saveData).then((res) => {
        if (res) {
          //关闭弹窗
          closeModal();
          okLoading.value = false;
          //刷新列表
          emit('success');
        }
      });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  //左侧人员树选择事件
  const handleuserTree = (node) => {
    currentRationCode = node.data.psnNum;
    console.log('222');
    workList.value.setTreeSelected([]);
    setTableData([]);
    Object.keys(selectedUser).forEach((key) => {
      try {
        selectedUser[key] = node.data[key];
      } catch (e) {
        console.error(e);
      }
    });
    //填充表单数据 人员和编码
    setFieldsValue(node.data);
  };

  let currentRationCode = ''; //当前项目编码
  let selectWork = [];

  //右侧项目树选择事件
  const handleWorkTree = (node) => {
    if (!currentRationCode) {
      createMessage.warning('请先选择左侧人员');
      // checkedKeys = [];
      workList.value.setTreeSelected([]);
      return;
    }
    let sumPoints = 1;
    Object.values(defaultData).forEach((value) => {
      sumPoints = parseFloat(value) * sumPoints;
    });
    let selectData = JSON.parse(JSON.stringify(node.data));
    console.log('node', node);
    selectWork = getDataSource();
    selectWork.push({
      rationName: selectData.title,
      rationCode: selectData.code,
      // psnName: selectedUser.psnName,
      // psnNum: selectedUser.psnNum,
      unit: 1,
      stdscore: selectData.desc,
      sumPoints: unifyNumber(sumPoints * parseFloat(selectData.desc)),
      workPoints: unifyNumber(sumPoints * parseFloat(selectData.desc)),
      ...selectedUser,
      ...defaultData,
    });
    // let nodes = checkedKeys.e.checkedNodes;
    // console.log('nodes', nodes);
    let newData = [];
    let originData = getDataSource() || [];
    let rationName = [];
    let rationCode = [];
    let newRationName = [];
    let newRationCode = [];
    selectWork.forEach((n) => {
      // let temp = {
      //   rationName: n.name,
      //   rationCode: n.code,
      //   // psnName: selectedUser.psnName,
      //   // psnNum: selectedUser.psnNum,
      //   unit: 1,
      //   stdscore: n.desc,
      //   sumPoints: unifyNumber(sumPoints * parseFloat(n.desc)),
      //   workPoints: unifyNumber(sumPoints * parseFloat(n.desc)),
      //   ...selectedUser,
      //   ...defaultData,
      // };
      rationName.push(n.rationName);
      rationCode.push(n.rationCode);
      newRationName = Array.from(new Set(rationName));
      newRationCode = Array.from(new Set(rationCode));
      // 新表格数据 原有的数据需要保留
      // originData.forEach((d) => {
      //   if (d['rationCode'] == temp.rationCode) {
      //     temp = Object.assign(d);
      //   }
      // });
      // newData.push(temp);
    });
    //数据保存需要添加的参数
    selectedWork = {
      ...selectedWork,
      rationName: newRationName.join(','),
      rationCode: newRationCode.join(','),
    };
    console.log('selectedWork', selectedWork);
    //重填表格数据
    console.log('重填数据', newData);
    setTableData(selectWork);
  };

  const scoreCompute = () => {
    let TableData = getDataSource();
    let column = getColumns();
    // TableData[]
    let currentRecord = TableData[currentTableIndex];
    let workPoints = null;
    if (!currentRecord.unit) {
      // 次数没填时 工作量得分为0    workPoints 工作量得分   qspoints质量得分
      currentRecord.workPoints = 0;
      currentRecord.sumPoints = currentRecord.workPoints;
    } else {
      // currentRecord.workPoints = currentRecord.rationForm
      workPoints = currentRecord.unit;
      column.forEach((c) => {
        if (c.type && currentRecord[c.dataIndex]) {
          workPoints = currentRecord[c.dataIndex] * workPoints;
          // counts.push
        }
      });
      currentRecord.workPoints = workPoints;
      currentRecord.sumPoints = currentRecord.workPoints;
    }
    if (currentRecord.stdscore) {
      currentRecord.workPoints = currentRecord.workPoints * parseFloat(currentRecord.stdscore);
    }
    if (currentRecord.qspoints || currentRecord.qspoints == 0) {
      currentRecord.sumPoints = currentRecord.qspoints + currentRecord.workPoints;
    }
    if (!currentRecord.qspoints) {
      currentRecord.sumPoints = currentRecord.workPoints;
    }
    // 精度转化
    currentRecord.workPoints = unifyNumber(currentRecord.workPoints);
    currentRecord.sumPoints = unifyNumber(currentRecord.sumPoints);
  };
  const getTableAction = (record, index) => {
    return [
      {
        label: '删除',
        onClick: handleDelete.bind(null, record, index),
      },
    ];
  };

  const handleDelete = async (record, index) => {
    let tableData = getDataSource();
    tableData.splice(index, 1);
    setTableData(tableData);
    // if (!record.id) {
    //   tableData.splice(index, 1);
    //   setTableData(tableData);
    // } else {
    //   await deleteOne({ id: record.id }, handleSuccess);
    // }
    // await deleteOne({ id: record.id }, handleSuccess);
  };
</script>

<style scoped lang="less">
  .table-container {
    height: 750px;
  }

  @media screen and(max-width: 1650px) {
    .table-container {
      height: 650px;
    }
  }

  @media screen and(max-width: 1500px) {
    .table-container {
      height: 600px;
    }
  }

  .bot-container {
    display: flex;
  }

  .bot-table-container {
    width: calc(100% - 250px);
  }

  /deep/.ant-input-number {
    width: 100%;
  }

  /deep/.ant-picker {
    width: 100%;
  }
</style>
